package com.huanshi.module.pms.controller;

import com.huanshi.common.CommonResult;
import com.huanshi.entity.PmsCategory;
import com.huanshi.module.pms.param.CategoryVo;
import com.huanshi.service.PmsCategoryService;
import com.huanshi.utils.BeanCopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品类目，Controller
 * 
 * @author 幻世
 * @date 2023-07-02
 */
@RestController
@RequestMapping("/api/pms/category")
public class PmsCategoryController {
    @Autowired
    private PmsCategoryService categoryService;

    /**
     * 查询商品类目，列表
     */
    @GetMapping("/list")
    public CommonResult list()
    {
//        List<CategoryVo> categoryList = new ArrayList<>();
        List<PmsCategory> list = categoryService.list();
        List<CategoryVo> categoryList = BeanCopyUtil.copyProperties(list, CategoryVo.class);

        List<CategoryVo> parentList = new ArrayList<>();

        parentList = categoryList.stream().filter(item -> item.getIsParent() == 1).collect(Collectors.toList());

        for (CategoryVo category: parentList) {
            category.setChildren(categoryList.stream().filter(i -> Objects.equals(i.getParentId(), category.getId())).collect(Collectors.toList()));
        }
        return CommonResult.success(parentList);
    }

    @GetMapping("/parentList")
    public CommonResult getParentCategory(){
        return CommonResult.success(categoryService.selectParentCategory());
    }
    /**
     * 获取商品类目，详细信息
     */

    @GetMapping("/{id}")
    public CommonResult getInfo(@PathVariable("id") Long id)
    {
        return CommonResult.success(categoryService.getById(id));
    }
    /**
     * 获取商品子类目
     */

    @GetMapping("/SubCategory/{pid}")
    public CommonResult getSubCategory(@PathVariable("pid") Long pid)
    {
        return CommonResult.success(categoryService.getChildrenById(pid));
    }

    /**
     * 新增商品类目，
     */
    @PostMapping
    public CommonResult add(@RequestBody PmsCategory category)
    {
        return CommonResult.success(categoryService.save(category));
    }

    /**
     * 修改商品类目，
     */
    @PutMapping
    public CommonResult edit(@RequestBody PmsCategory category)
    {
        return CommonResult.success(categoryService.updateById(category));
    }

    /**
     * 删除商品类目，
     */
	@DeleteMapping("/del/batch")
    public CommonResult remove(@RequestBody List<Integer> ids)
    {
        return CommonResult.success(categoryService.removeByIds(ids));
    }
}
